package com.goodboys.base.filter;

import com.goodboys.base.utils.RedisClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by CJ on 2018-05-24.
 */
//@Order(0)
//@Component
//@WebFilter(filterName = "baseFilter", urlPatterns = "/*")
public class BaseFilter implements Filter{

    private Logger logger = LoggerFactory.getLogger(BaseFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        try {
            //获取是lat,lng字段
            String lat = request.getParameter("lat");
            String lng = request.getParameter("lng");

            if (StringUtils.isEmpty(lat) || StringUtils.isEmpty(lng)) {
                //经纬度存在为空，报错
                if("GET".equals(request.getMethod()))
                    request.getRequestDispatcher("/sys/error?message=经纬度存在为空,请重试。。。").forward(request, response);
                else
                    request.getRequestDispatcher("/sys/postError?message=经纬度存在为空,请重试。。。").forward(request, response);
                logger.warn("经纬度存在为空,请重试。。。");
                return;
            }else {
                chain.doFilter(req, res);
            }
        } catch (NullPointerException e) {
            //经纬度存在为空，报错
            if("GET".equals(request.getMethod()))
                request.getRequestDispatcher("/sys/error?message=经纬度存在为空,请重试。。。").forward(request, response);
            else
                request.getRequestDispatcher("/sys/postError?message=经纬度存在为空,请重试。。。").forward(request, response);
            logger.warn("经纬度存在为空,请重试。。。");
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
